package swing_framework;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSlider;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import processing_model.Display3D;
import processing_model.Paint2D;

import action.NodeSelectAction;

import Utils.CalendarPanel;
import Utils.GBC;
import data_generator.entity.SensorNode;
import data_generator.entity.Temperature;
import data_generator.xml.XMLConfig;
import data_transfer.DataCollections;

public class ParameterPanel {

	/**
	 * @param args
	 */
	private JPanel leftPanel;
	private JPanel paraPanel;
	private JLabel start_time_label;
	private JLabel end_time_label;
	private JTextField start_time_field;
	private JTextField end_time_field;
	private CalendarPanel startCp = CalendarPanel.getInstance();
	private CalendarPanel endCp = CalendarPanel.getInstance();
	private JComboBox<String> starthour_choice;
	private JComboBox<String> endhour_choice;
	private JButton fetch_button;
	private JButton reset_button;

	private JPanel sliderPanel;
	private JSlider time_cursor_slider;
	private JPanel subParaPanel;
	private JPanel nodeListPanel;
	private JPanel colorbarPanel;
	
	//
	private Paint2D paint2d;
	private Display3D display3d;
	public JPanel createParameterPanel(Display3D display3d) {
		paint2d = new Paint2D();
		paint2d.init();
		paint2d.setup();
		paint2d.firstDraw();
		this.display3d = display3d;
		leftPanel = new JPanel();
		leftPanel.setLayout(new BorderLayout());
		leftPanel.setBorder(BorderFactory.createEtchedBorder());
		

		paraPanel = new JPanel();
		paraPanel.setBorder(BorderFactory.createEtchedBorder());
		paraPanel.setLayout(new BorderLayout());
		paraPanel.setPreferredSize(new Dimension(1366, 80));

	

		subParaPanel = new JPanel();
		subParaPanel.setPreferredSize(new Dimension(766, 80));
		subParaPanel.setLayout(new GridBagLayout());
		

		start_time_label = new JLabel("Start Time:");
		
		subParaPanel.add(start_time_label, new GBC(0, 0, 1, 1)
				.setFill(GBC.BOTH).setWeight(1, 1).setInsets(5, 5, 5, 5));

		start_time_field = new JTextField();
		startCp.register(start_time_field);
		
		subParaPanel.add(start_time_field, new GBC(1, 0, 1, 1)
				.setFill(GBC.BOTH).setWeight(1, 1).setInsets(5, 5, 5, 5));

		starthour_choice = new JComboBox<String>();
		starthour_choice.addItemListener(new SimpleItemListener());
		for (int i = 0; i < 24; i++) {
			starthour_choice.addItem(Integer.toString(i));
		}
		
		subParaPanel.add(starthour_choice, new GBC(2, 0, 1, 1)
				.setFill(GBC.BOTH).setWeight(1, 1).setInsets(5, 5, 5, 5));

		end_time_label = new JLabel("End Time:");
		
		subParaPanel.add(end_time_label, new GBC(0, 1, 1, 1).setFill(GBC.BOTH)
				.setWeight(1, 1).setInsets(5, 5, 5, 5));

		end_time_field = new JTextField();
		endCp.register(end_time_field);
		
		subParaPanel.add(end_time_field, new GBC(1, 1, 1, 1).setFill(GBC.BOTH)
				.setWeight(1, 1).setInsets(5, 5, 5, 5));

		endhour_choice = new JComboBox<String>();
		endhour_choice.addItemListener(new SimpleItemListener());
		for (int i = 0; i < 24; i++) {
			endhour_choice.addItem(Integer.toString(i));
		}
		
		subParaPanel.add(endhour_choice, new GBC(2, 1, 1, 1).setFill(GBC.BOTH)
				.setWeight(1, 1).setInsets(5, 5, 5, 5));

		fetch_button = new JButton("Fetch");
		fetch_button.setPreferredSize(new Dimension(25, 10));
		fetch_button.addActionListener(new SimpleListner());
		subParaPanel.add(fetch_button, new GBC(3, 1, 1, 1).setFill(GBC.BOTH)
				.setWeight(1, 1).setInsets(5, 5, 5, 5));

		reset_button = new JButton("Reset");
		reset_button.setPreferredSize(new Dimension(25, 10));
		reset_button.addActionListener(new SimpleListner());
		subParaPanel.add(reset_button, new GBC(3, 0, 1, 1).setFill(GBC.BOTH)
				.setWeight(1, 1).setInsets(5, 5, 5, 5));
		
		paraPanel.add(subParaPanel, BorderLayout.WEST);
		
		
		nodeListPanel=new JPanel();
		nodeListPanel.setLayout(new GridBagLayout());
		nodeListPanel.setPreferredSize(new Dimension(266,80));
		@SuppressWarnings("rawtypes")
		Iterator it = XMLConfig.nodeMap.keySet().iterator();
		while (it.hasNext()) {
			SensorNode sn = (SensorNode) it.next();
			JCheckBox cb = new JCheckBox(sn.getName(), true);
			cb.addActionListener(new NodeSelectAction(sn));
			int i=0,j=0;
			if (sn.getName().equals("Node1")) {
				i=0;j=0;
			}else if (sn.getName().equals("Node2")) {
				i=1;j=0;
			}else if (sn.getName().equals("Node3")) {
				i=2;j=0;
			}else if (sn.getName().equals("Node4")) {
				i=3;j=0;
			}else if (sn.getName().equals("Node5")) {
				i=0;j=1;
			}else if (sn.getName().equals("Node6")) {
				i=1;j=1;
			}else if (sn.getName().equals("Node7")) {
				i=2;j=1;
			}else if (sn.getName().equals("Node8")) {
				i=3;j=1;
			}
			
			nodeListPanel.add(cb, new GBC(i, j));
		}
        paraPanel.add(nodeListPanel,BorderLayout.CENTER);	
        
        Image image;
		try {
			image = ImageIO.read(new File("./images/colorbar.png"));
			colorbarPanel=new ImagePanel(image);
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}       
        colorbarPanel.setPreferredSize(new Dimension(260,80));
        paraPanel.add(colorbarPanel,BorderLayout.EAST);
        
        
		leftPanel.add(paraPanel, BorderLayout.CENTER);
		
		
		sliderPanel = new JPanel();
		sliderPanel.setPreferredSize(new Dimension(1366, 44));
		sliderPanel.setLayout(new BorderLayout());
		@SuppressWarnings("rawtypes")
		Iterator iterator = XMLConfig.nodeMap.values().iterator();
		if (iterator.hasNext()) {
			@SuppressWarnings("unchecked")
			ArrayList<Temperature> tList = (ArrayList<Temperature>) iterator
					.next();
			time_cursor_slider = new JSlider(SwingConstants.HORIZONTAL, 0,
					tList.size(), 0);
		}

		time_cursor_slider.setBackground(Color.CYAN);
		time_cursor_slider.setMajorTickSpacing(50);
		time_cursor_slider.setMinorTickSpacing(10);
		time_cursor_slider.setPaintTicks(true);
		time_cursor_slider.getValue();
		time_cursor_slider.setVisible(true);
		time_cursor_slider.addChangeListener(new ChangeListener() {

			@Override
			public void stateChanged(ChangeEvent e) {
				JSlider source = (JSlider)e.getSource();
				if(source.getValueIsAdjusting())
					return;
				Map<SensorNode, Temperature> sensorInfos = XMLConfig.getNodeTemperatureByPos(source.getValue());
				
				paint2d.draw(sensorInfos);
				ParameterPanel.this.display3d.refreshImage();
			}
		});

		sliderPanel.add(time_cursor_slider, BorderLayout.CENTER);
		leftPanel.add(sliderPanel, BorderLayout.SOUTH);

		return leftPanel;
	}

	private class SimpleItemListener implements ItemListener {

		@Override
		public void itemStateChanged(ItemEvent e) {

			if (e.getSource() == starthour_choice) {
				System.out.println(starthour_choice.getSelectedItem()
						.toString());
			} else if (e.getSource() == endhour_choice) {
				System.out.println(endhour_choice.getSelectedItem().toString());
			}
		}
	}

	private class SimpleListner implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {

			if (e.getSource() == fetch_button) {
				try {

					// Map<SensorNode, Temperature> st =
					// XMLConfig.getNodeTemperatureByPos(time_cursor_slider.getValue());
					cleanResult();
					// time_cursor_slider.setValue(0);
					// String start_datetime = start_time_field.getText() + "T"
					// + starthour_choice.getSelectedItem().toString()
					// + ":00:00";
					// String end_datetime = end_time_field.getText() + "T"
					// + endhour_choice.getSelectedItem().toString()
					// + ":00:00";
					//
					// String strStartTime = start_time_field.getText() + " "
					// + starthour_choice.getSelectedItem().toString()
					// + ":00:00";
					// String strEndTime = end_time_field.getText() + " "
					// + endhour_choice.getSelectedItem().toString()
					// + ":00:00";
					// if (end_datetime.compareTo(start_datetime)<0) {
					// JOptionPane.showMessageDialog(new Frame(),
					// "The end time cannot be earlier than the start time!",
					// "Error",
					// JOptionPane.ERROR_MESSAGE);
					// return;
					// }
					//
					// SimpleDateFormat sdf = new
					// SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					// final Date starttime = sdf.parse(strStartTime);
					// final Date endtime = sdf.parse(strEndTime);
					// long sec = (endtime.getTime() -
					// starttime.getTime())/1000;
					// int min = (int) (sec / 60);
					// time_cursor_slider.setMaximum(min);
					// time_cursor_slider.setVisible(true);
					// time_cursor_slider.addChangeListener(new ChangeListener()
					// {
					//
					// @Override
					// public void stateChanged(ChangeEvent e) {
					// Calendar cal = Calendar.getInstance();
					// cal.setTime(starttime);
					// cal.add(Calendar.MINUTE,time_cursor_slider.getValue());
					// SimpleDateFormat sdf = new
					// SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					// System.out.println(sdf.format(cal.getTime()));
					// }
					// });

					// System.out.print(start_datetime);
					// System.out.println(end_datetime);

					// DataCollections.dataEntities = DataFetch.FetchData(
					// node_id_field.getText(),
					// start_datetime,
					// end_datetime);
					// Iterator it = XMLConfig.nodeMap.keySet().iterator();
					// while (it.hasNext()) {
					//
					// DataFetch.FetchData(
					// (SensorNode)it.next(),
					// start_datetime,
					// end_datetime);
					// }
					//

					// if (DataCollections.dataEntities == null
					// || 0 == DataCollections.dataEntities.size()) {
					// JOptionPane.showMessageDialog(new Frame(),
					// "Incorrect parameter!", "Error",
					// JOptionPane.ERROR_MESSAGE);
					// }
					// DataPanel.updateTable();
				} catch (Exception e1) {
					System.out.println("error");
				}
			} else if (e.getSource() == reset_button) {
				//node_id_field.setText(null);
				start_time_field.setText(null);
				starthour_choice.setSelectedIndex(0);
				endhour_choice.setSelectedIndex(0);
				end_time_field.setText(null);
				DataCollections.dataEntities.clear();
				DataPanel.updateTable();
			} else {

			}
		}

	}

	@SuppressWarnings("unchecked")
	private void cleanResult() {
		@SuppressWarnings("rawtypes")
		Iterator it = XMLConfig.nodeMap.values().iterator();
		while (it.hasNext()) {
			((ArrayList<Temperature>) it.next()).clear();
		}
	}

	
}
